package com.zen.lon.open.proxy;

import com.zen.lon.open.remote.spi.ServiceBootstrap;
import com.zen.lon.open.remote.utils.LogUtils;
import java.lang.reflect.Proxy;

/**
 * 代理工厂，用于创建代理
 *
 * @author ZonLen since on 2021/7/12 下午1:28
 */
public class ProxyAgentFactory {

  private static ProxyAgentMetaDataReader proxyAgentMetaDataReader;

  private Object proxy;

  /**
   * JDK代理 代理工厂创建代理对象
   */
  public synchronized <P> P newProxy(Class<P> proxyClass) {
    if (proxyAgentMetaDataReader == null) {
      proxyAgentMetaDataReader = ServiceBootstrap.loadPrimary(ProxyAgentMetaDataReader.class);
    }
    if (null == this.proxy) {
      proxyAgentMetaDataReader.parseProxyClass(proxyClass);
      LogUtils.info(ProxyAgentFactory.class, "class[{}] ProxyAgentFactory dynamic proxy",
          proxyClass.getName());
      final ProxyAgentMethod proxyAgentMethod = new ProxyAgentMethod(proxyClass);
      this.proxy = Proxy.newProxyInstance(proxyClass.getClassLoader(), new Class[]{proxyClass},
          proxyAgentMethod);
    }
    return (P) proxy;
  }


}
